import React from 'react'
import { Button, Form, Input, message, Space, Tag } from 'antd'
import { PermissionKey, type User } from '../../server/interface'
import { api_user } from '../apis'
import { connect, getState, hasPermission } from '../store'

const LOGOUT_URL = (window as any).LOGOUT_URL
export interface ProfileProps {
    loginUser: User
}

const Profile = (props: ProfileProps) => {
    const { loginUser } = props
    const [form] = Form.useForm()
    const onFinish = (values: any) => {
        const { newPassword, confirmNewPassword } = values
        if (newPassword !== confirmNewPassword) {
            message.warning('两次输入的密码不一致')
        } else {
            api_user.updatePassword({newPassword}).then((res) => {
                if (res.success) {
                    message.success('修改密码成功')
                    form.resetFields()
                } else {
                    message.error(res.msg)
                }
            })
        }
    }
    return (
        <div style={{maxWidth: 600}}>
            <h1>{loginUser.nickname}</h1>
            <p>用户名：{loginUser.username} {loginUser.readonly && <Tag color="blue">系统用户</Tag>}
                {LOGOUT_URL && <Button type="link" href={LOGOUT_URL}>退出登录</Button>}
            </p>
            <p>角色：{loginUser.rolesInfo?.map(r => <Tag key={r.key}>{r.name}</Tag>)}</p>
            <p>&nbsp;</p>
            {hasPermission(PermissionKey.RBAC_SELF) && <Form form={form} onFinish={onFinish} wrapperCol={{span: 20}} labelCol={{span: 4}}>
                <Form.Item label="新密码" name={'newPassword'} required rules={[
                    { required: true, message: '请输入新密码' },
                    { min: 6, message: '密码长度不能少于6位' },
                    { max: 16, message: '密码长度不能超过16位' },
                ]}>
                    <Input.Password />
                </Form.Item>
                <Form.Item label="确认新密码" name={'confirmNewPassword'} required rules={[
                    { required: true, message: '请确认新密码' },
                    { min: 6, message: '密码长度不能少于6位' },
                    { max: 16, message: '密码长度不能超过16位' },
                ]}>
                    <Input.Password />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">修改密码</Button>
                </Form.Item>
            </Form>}
        </div>
    )
}

export default connect(() => {
    const { loginUser } = getState()
    return { loginUser }
})(Profile)